package com.example.learningnote.giftbox;

import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager2.widget.ViewPager2;

import com.example.learningnote.R;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.List;

/**
 * 主活动，展示礼物墙
 */
public class GiftBoxActivity extends AppCompatActivity {
    private GiftViewModel viewModel;
    private GiftPagerAdapter pagerAdapter;
    private boolean useGiftList1 = true; // 模拟服务端数据切换
    private TextView selectedGiftInfo; // 添加 TextView 成员变量

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gift_box);


        selectedGiftInfo = findViewById(R.id.selectedGiftInfo);
        Log.d("MainActivity-Entry", "onCreate ");
        // 初始化 ViewModel
        viewModel = new ViewModelProvider(this).get(GiftViewModel.class);

        // 初始化 ViewPager2
        ViewPager2 viewPager = findViewById(R.id.viewPager);
        pagerAdapter = new GiftPagerAdapter();
        viewPager.setAdapter(pagerAdapter);

        TabLayout tabLayout = findViewById(R.id.tabLayout);
        new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> {}).attach();

        // 设置礼物点击监听
        pagerAdapter.setOnGiftClickListener(gift -> viewModel.selectGift(gift.getId()));

        // 观察礼物列表变化 注册观察者
        viewModel.getGiftList().observe(this, gifts -> {
            Log.d("MainActivity-Entry", "Gift list updated: " + (gifts != null ? gifts.size() : "null"));
            pagerAdapter.updateGifts(gifts);
        });

        // 观察选中状态变化
        viewModel.getSelectedGiftId().observe(this, selectedGiftId -> {
            Log.d("MainActivity-Entry", "Selected gift ID: " + selectedGiftId);
            pagerAdapter.updateSelectedGiftId(selectedGiftId);
            List<Gift> gifts = viewModel.getGiftList().getValue();
            if (gifts != null && selectedGiftId != null) {
                for (Gift gift : gifts) {
                    if (gift.getId().equals(selectedGiftId)) {
                        selectedGiftInfo.setText("选中礼物: ID=" + gift.getId() + ", Name=" + gift.getGiftName());
                        return;
                    }
                }
            }
            selectedGiftInfo.setText("未选择礼物");
        });

        // 初始加载 giftList1
        Log.d("MainActivity-Entry", "Initializing gift list with useGiftList1: " + useGiftList1);
        viewModel.initGiftList(true);

        Button button = findViewById(R.id.change_gift_data_btn);
        button.setOnClickListener(v -> {
            useGiftList1 = !useGiftList1;
            Log.d("MainActivity-Entry", "Switching to gift list: " + useGiftList1);
            viewModel.initGiftList(useGiftList1);
        });

    }
}


